/**
 * 
 */
package co.fitstart.tencent.customer.web.controller.auth.web;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.demo2do.core.entity.result.HttpResult;
import com.demo2do.core.wechat.entity.auth.WebAuthLogin;

import co.fitstart.entity.user.WechatAccount;
import co.fitstart.tencent.customer.entity.webauth.WebAuth;
import co.fitstart.tencent.customer.service.WebAuthService;

/**
 * @author downpour
 *
 */
@RestController
@RequestMapping("/wechat/web-auth")
public class WebAuthRestController {
    
    private static final Logger logger = LoggerFactory.getLogger(WebAuthRestController.class);
    
    @Autowired
    private WebAuthService webAuthService;
    
    /**
     * 
     * @param uuid
     * @return
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public HttpResult getWebAuth(@RequestParam("uuid") String uuid) {
        
        logger.info("#getWebAuth() - start get web_auth result with uuid[{}]", uuid);
        
        HttpResult httpResult = new HttpResult();
        
        // load web_auth_response, include user_info if scope is USERINFO
        WebAuth webAuth = webAuthService.loadWebAuth(uuid);
        
        if(webAuth.isValid()) {  // valid response
            
            WebAuthLogin webAuthLogin = new WebAuthLogin(webAuth.getScope(), webAuth.getOpenid(), webAuth.getUnionid(), webAuth.getRedirectUrl());
            
            // also put back wechat account if exists
            WechatAccount wechatAccount = webAuth.getAccount();
            
//            if(wechatAccount != null) {
//                webAuthLogin.account(wechatAccount.getHeadimgurl(), wechatAccount.getNickname(), wechatAccount.getSex(), wechatAccount.getSubscribeTimeAsDate(), wechatAccount.getUnionid());
//            }
            
            httpResult.data("web_auth_login", webAuthLogin);
            
            return httpResult.success();
        }
        
        return httpResult.fail("500").message("INVALID_AUTH_REQUEST");
    }

}
